const app = getApp()
const {Toast} = app.globalData

import {getUserInfo} from "../../../../api/userInfo"
import {createReport} from "../../../../api/report"
import {formatTime} from "../../../../utils/utils"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    fileList: [],
    count:0,
    location:"",
    description:"",
    category:"",
    createdTime:"",
    score:10,
    process:[],
    showPopup:false,
    categoryArr:["车辆乱停","随意堆放","公物损坏","社区卫生","其它"]
  },
  async onLoad(){
    let ret = await getUserInfo()
    this.setData({
      creatorId:ret._id
    })
  },
  // 统计上传图片
  afterRead(event) {
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    
    let fileList = this.data.fileList

    fileList.push(file)

    this.setData({
      fileList,
      count:fileList.length
    })
  },
  // 删除图片
  deleteImg(e){
    const {index} = (e.detail);

    let fileList = this.data.fileList

    fileList.splice(index,1)

    this.setData({
      fileList,
      count:fileList.length
    })
  },

  // 控制弹出层
  handleShowPopup(){
    this.setData({
      showPopup:!this.data.showPopup
    })
  },

  // 选择问题分类
  chooseCategory(e){
    this.setData({
      showPopup:!this.data.showPopup,
      category:e.detail.value
    })
  },

  // 提交数据
  async submit(){
    Toast.loading("上传中...")
    let {fileList,description,location,category,process,score,creatorId} = this.data

    if(this.validate(fileList,description,location,category)){
      let imgUrls = await this.uploadImgs()
      let createdTime = formatTime(Date.now())
      process.push({
        state:"问题已上报",
        time:createdTime
      })
      let ret = await createReport({
        imgUrls,
        description,
        location,
        category,
        process,
        createdTime,
        score,
        creatorId
      })

      if(ret.code == 201){
        Toast.success("上报成功")
        this.initData()
      }
    }
  },
  // 校验数据的有效性
  validate(fileList,description,location,category){
    if(fileList.length == 0 || description.length < 5 || location.length == 0 || category.length == 0){
      Toast.fail("请完成相应输入后再提交")
      return false
    }else{
      return true
    }
  },
  // 上传图片至服务器
   uploadImgs(){
    let imageUrls = []
    let {fileList} = this.data
    return new Promise((resolve,reject)=>{
      fileList.map(item=>{
        wx.uploadFile({
          filePath: item.url,
          name: 'imageInfo',
          url: 'http://127.0.0.1:3000/report/image/upload',
          success(res){
            let data = JSON.parse(res.data)
            if(data.code){
              imageUrls.push(data.downUrl)
              if(imageUrls.length === fileList.length){
                // console.log(imageUrls);
                resolve(imageUrls)
              }
            }
          },
          fail(e){
            reject(e)
          }
        })
      })
    })
  },
  // 数据初始化
  initData(){
    this.setData({
      fileList: [],
      count:0,
      location:"",
      description:"",
      category:"",
      createdTime:"",
      process:[],
      showPopup:false,
    })
  }
})